﻿
using Castle.Core.Internal;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OL_AccessoryMagInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {

        public List<OL_FilterDTO> Filters;
        public int NoQueryNum { get; set; }

        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public OL_AccessoryMagInterfaceBusiness()
        {
            this.InterfaceName = "One_link配件管理";
            //字段的映射关系
            tableField = GetMapField("getFilterRows");
            //索引字段
            Keys = GetKeys("getFilterRows");
            //indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();
            Filters.Add(
                new OL_FilterDTO() { ControlId = "66ce7f941214257ad13bf254", DataType = 2, SpliceType = 1, FilterType = 8, Value = "" }//人工填写跟踪号不为空
            );
            Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "68c7a95c075cb3166a16bb4a", DataType = 29, SpliceType = 1, FilterType = 7, Value = "" }//系统关联物流信息为空
           );
            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT  * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置

            //查询执行中的事件
            OnQueryEvent += Interface_Business_OnQueryEvent; ;
            //查询执行前的事件
            BeforeQueryEvent += Interface_Business_BeforeQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += Interface_Business_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void Interface_Business_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }
        }


        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 新增更新表
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {

                await GetRows();
                //获取目标数据
                //List<ReturnMag> targetData = new List<ReturnMag>();//目标据集合
                //targetData = await QueryAsync<ReturnMag>(queryOption, tableField, SqlDb);

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }


        /// <summary>
        /// 新增更新表
        /// </summary>
        public async Task<List<OL_AccessoryMag>> GetRows(List<OL_FilterDTO> oL_Filters = null)
        {
            if (oL_Filters != null)
            {
                this.Filters.Clear();
                this.Filters.AddRange(oL_Filters);
            }

            List<OL_AccessoryMag> rows = new List<OL_AccessoryMag>();//目标据集合
            try
            {
                //获取目标数据
                rows = await QueryAsync<OL_AccessoryMag>(queryOption, tableField, SqlDb);
                foreach (var item1 in rows)
                {

                    List<AssTable> table = item1.SKU.ToObject<List<AssTable>>();
                    item1.SKU_T = !table.IsNullOrEmpty() && table.Count > 0 ? table[0] : new AssTable() { name = "" };
                    item1.SKU = item1.SKU_T.name;
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
            return rows;
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }



}
